package com.brotherly.mpgp;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.brotherly.framework.BaseActivity;
import com.brotherly.framework.app.BaseApplication;
import com.brotherly.mpgp.remoteinterface.RemoteServerWatcher;
import com.brotherly.mpgp.view.DownLoadButton;
import com.brotherly.mpgp.view.UpdateFreshListView;
import com.brotherly.util.downloader.DownLoaderUtil;

public class FavoriteActivity extends BaseActivity {

    private DecimalFormat mFileSizeFomat = new DecimalFormat("0.00M");

    private class CheatsListAdapter extends BaseAdapter implements OnItemClickListener
    {
        private LayoutInflater mInflater;

        private int[] mIds;

        private boolean mIsShowPic = true;

        public CheatsListAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from(context);
            mIds = getFavoriteArticleIds();
            mIsShowPic = getSharedPreferences("Setting", MODE_PRIVATE).getBoolean("isShowPic", false);
        }

        @Override
        public int getCount()
        {
            return mIds.length;
        }

        @Override
        public Object getItem(int position)
        {
            int id = mIds[position];
            return getFavoriteArticle(id);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            convertView = (ViewGroup) mInflater.inflate(R.layout.article_list_item, null);
            if (position % 2 == 0)
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_1);
            } else
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_2);
            }
            try
            {
                JSONObject item = (JSONObject) getItem(position);
                String type = item.getString("type");

                TextView title = (TextView) convertView.findViewById(R.id.tv_article_list_item_title);
                title.setText(item.getString("title"));
                View typeView = convertView.findViewById(R.id.v_type);
                Button getAccount = (Button) convertView.findViewById(R.id.btn_get_account);
                JSONObject info = null;
                JSONObject action = null;
                if (item.has("info"))
                {
                    info = item.getJSONObject("info");
                    if (info.has("action"))
                    {
                        JSONArray actions = info.getJSONArray("action");
                        if (actions.length() > 0)
                        {
                            action = actions.getJSONObject(0);
                        }
                    }
                }
                ImageView imageview = (ImageView) convertView.findViewById(R.id.iv_article_list_item_image);
                // imageview.setVisibility(View.GONE);
                if (mIsShowPic)
                {
                    imageview.setVisibility(View.VISIBLE);
                    loadArticleFirstImage(item, imageview);
                    title.setLines(2);
                } else
                {
                    imageview.setVisibility(View.GONE);
                    title.setLines(1);
                }

                if (action != null)
                {
                    getAccount.setVisibility(View.VISIBLE);
                } else
                {
                    getAccount.setVisibility(View.GONE);
                }
                if ("course".equals(type))
                {
                    typeView.setBackgroundColor(0xff7ac3c9);
                } else
                {
                    typeView.setBackgroundColor(0xfffc7a7e);
                }

                TextView content = (TextView) convertView.findViewById(R.id.tv_article_content);
                if (mIsShowPic)
                {
                    content.setVisibility(View.GONE);
                } else
                {
                    content.setVisibility(View.VISIBLE);
                    String contentStr = item.getString("content");
                    JSONArray contents = new JSONArray(contentStr);
                    for (int i = 0; i < contents.length(); i++)
                    {
                        if ("para".equals(contents.getJSONObject(i).getString("type")))
                        {
                            content.setText(contents.getJSONObject(i).getString("content"));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return convertView;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Intent intent = new Intent(FavoriteActivity.this, ArticleActivity.class);
            JSONArray articles = new JSONArray();
            int count = getCount();
            for (int i = 0; i < count; i++)
            {
                articles.put(getItem(i));
            }
            intent.putExtra("Articles", articles.toString());
            intent.putExtra("isShowRelatedGame", true);
            intent.putExtra("Index", position - 1);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            startActivity(intent);
        }

        @Override
        public void notifyDataSetChanged()
        {
            mIds = getFavoriteArticleIds();
            mIsShowPic = getSharedPreferences("Setting", MODE_PRIVATE).getBoolean("isShowPic", false);
            super.notifyDataSetChanged();
        }
    }

    class RecommendListAdapter extends BaseAdapter implements OnItemClickListener
    {
        @SuppressWarnings("unused")
        private Context mContext;
        private int[] mIds;
        private LayoutInflater mInflater;

        public RecommendListAdapter(Context context)
        {
            super();
            this.mContext = context;
            this.mInflater = LayoutInflater.from(context);
            mIds = getFavoriteGameIds();
        }

        @Override
        public int getCount()
        {
            return mIds.length;

        }

        @Override
        public Object getItem(int position)
        {
            return getFavoriteGame(mIds[position]);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
            {
                convertView = (ViewGroup) mInflater.inflate(R.layout.main_recommend_list_item, null);
            }
            if (position % 2 == 0)
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_1);
            } else
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_2);
            }
            JSONObject gameinfo = (JSONObject) getItem(position);

            try
            {
                String name = gameinfo.getString("name");

                if (gameinfo.has("info"))
                {
                    JSONObject info = gameinfo.getJSONObject("info");
                    if (info.has("players"))
                    {
                        ((TextView) convertView.findViewById(R.id.btn_game_tag_2)).setText("" + info.getInt("players"));
                    }
                    if (info.has("size"))
                    {
                        int size = info.getInt("size");
                        String fileSizeStr = mFileSizeFomat.format(size / 1024d / 1024d);
                        ((TextView) convertView.findViewById(R.id.btn_game_tag_1)).setText(fileSizeStr);
                    }
                }

                ((TextView) convertView.findViewById(R.id.tv_game_list_item_gamename)).setText(name);

                ImageView icon = ((ImageView) convertView.findViewById(R.id.iv_game_list_item_icon));

                int id = gameinfo.getInt("id");

                String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                        .append("games/blob?key=image&gameref=")
                        .append(id).toString();

                imageViewLoadInternetResource(icon, imageurl, R.drawable.grap_icon);

                String packages = null;
                int fileSize = 0;
                if (gameinfo.has("info"))
                {
                    JSONObject info = gameinfo.getJSONObject("info");
                    try
                    {
                        packages = info.getString("package");
                        fileSize = info.getInt("size");
                    }
                    catch (JSONException e)
                    {
                        Log.d("TAG", "info not packages ");
                    }
                }

                int gameId = gameinfo.getInt("id");
                DownLoadButton dlButton = (DownLoadButton) convertView.findViewById(R.id.dl_button);
                if (packages == null)
                {
                    dlButton.setVisibility(View.INVISIBLE);
                }
                else
                {
                    dlButton.setVisibility(View.VISIBLE);
                    dlButton.setFileSize(fileSize);
                    dlButton.setKey(gameId, name);
                    DownloadEvent event = mDownloadEvents.get(dlButton.getUrl());
                    if (event != null)
                    {
                        if (event.id.equals(DownLoaderUtil.Activity_Event_FileDownload_Info))
                        {
                            int param1 = (Integer) event.param1;
                            if (1 == param1)
                            {
                                JSONObject json = (JSONObject) event.param2;
                                dlButton.setDownLoading();
                                dlButton.setFileSize(json.getInt("fileSize"));
                                dlButton.setComplete(json.getInt("compelete"));
                                dlButton.showProgress();

                                Log.d(dlButton.getUrl(), "Param = 1 FileSize : " + dlButton.getFileSize()
                                        + "    Complete:" + dlButton.getComplete());
                                if (dlButton.getFileSize() <= dlButton.getComplete())
                                {
                                    Log.d(dlButton.getUrl(), "下载完成！");
                                    dlButton.stopDownload();
                                    dlButton.setStatusText();
                                    mDownloadEvents.remove(dlButton.getUrl());
                                }
                            } else if (0 == param1)
                            {
                                dlButton.setPause();
                                dlButton.invalidate();
                            }
                        } else if (event.id.equals(DownLoaderUtil.Activity_Event_FileDownload_Pause))
                        {
                            dlButton.setPause();
                            dlButton.invalidate();
                        } else if (event.id.equals(DownLoaderUtil.Activity_Event_FileDownload_Start))
                        {
                            dlButton.setDownLoading();
                            dlButton.setStatusText();
                        }
                    } else
                    {
                        dlButton.checkLocalFile();
                    }
                }

            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
            convertView.setTag(gameinfo);

            return convertView;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            try
            {
                JSONObject item = (JSONObject) getItem(position - 1);
                if (item != null)
                {
                    Intent intent = new Intent(FavoriteActivity.this, GameDetailActivity.class);
                    int gameref = item.getInt("id");
                    intent.putExtra("gameref", gameref);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    if (item.has("identifiers"))
                    {
                        JSONArray identifiers = item.getJSONArray("identifiers");
                        if (identifiers.length() > 0)
                        {
                            intent.putExtra("packageName", identifiers.getString(0));
                            startActivity(intent);
                        }
                    }
                }
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }

        @Override
        public void notifyDataSetChanged()
        {
            mIds = getFavoriteGameIds();
            super.notifyDataSetChanged();
        }

    }

    private class MainPagerAdapter extends PagerAdapter implements OnPageChangeListener {

        private ArrayList<LinearLayout> mViews = null;

        public MainPagerAdapter(ArrayList<LinearLayout> views)
        {
            this.mViews = views;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            container.removeView(mViews.get(position));
        }

        @Override
        public int getCount()
        {
            return mViews.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            ViewGroup.LayoutParams lp = null;
            lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);

            container.addView(mViews.get(position), lp);
            return mViews.get(position);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1)
        {
            return arg0 == arg1;
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
        {}

        @Override
        public void onPageScrollStateChanged(int status)
        {}

        @Override
        public void onPageSelected(int position)
        {
            if (position == 0)
            {
                towardToGame();
            } else if (position == 1)
            {
                towardToStrategy();
            }
        }
    }

    private ViewPager mViewPager;
    private LinearLayout mCheatsLayout;
    private UpdateFreshListView mCheatsListView;
    private CheatsListAdapter mCheatsListAdapter;

    private LinearLayout mRecommendLayout;
    private UpdateFreshListView mRecommendListView;
    private RecommendListAdapter mRecommendListAdapter;

    private MainPagerAdapter mMainPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorite);
        mViewPager = (ViewPager) findViewById(R.id.vp_main);
        mGameButton = findViewById(R.id.rl_game);
        mGameButton.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                towardToGame();
            }
        });
        mGame = (TextView) findViewById(R.id.tv_game);
        mArticleButton = findViewById(R.id.rl_article);
        mArticle = (TextView) findViewById(R.id.tv_article);
        mArticleButton.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                towardToStrategy();
            }
        });
    }

    private void showSDCardError()
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                AlertDialog alertDialog = new AlertDialog.Builder(FavoriteActivity.this)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.cancel();
                            }
                        }).setMessage("您手机未安装SD，请安装后在使用下载功能。").create();
                alertDialog.show();
            }
        });
    }

    private void showDownloadLongClick(Object param2)
    {
        final Object p2 = param2;
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(FavoriteActivity.this);
                alertDialog.setTitle("菜单");
                alertDialog.setItems
                        (
                                R.array.downloadmenu, new DialogInterface.OnClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                        DownLoadButton dlBut = (DownLoadButton) p2;
                                        switch (which)
                                        {
                                            case 0:
                                            {
                                                dlBut.installAPK();
                                                break;
                                            }
                                            case 1:
                                            {
                                                dlBut.deleteDownLoadFile();
                                                break;
                                            }
                                        }
                                    }
                                }
                        );
                alertDialog.show();

            }
        });
    }

    @Override
    protected void onServiceEvent(String id, Object param1, Object param2)
    {
        if (Activity_Event_Internet_Resource_Download_Success.equals(id))
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    mCheatsListAdapter.notifyDataSetChanged();
                    mRecommendListAdapter.notifyDataSetChanged();
                }
            });
        } else if (DownLoaderUtil.Activity_Event_FileDownload_Info.equals(id))
        {
            if (1 == (Integer) param1)
            {
                DownloadEvent event = new DownloadEvent();
                event.id = DownLoaderUtil.Activity_Event_FileDownload_Info;
                event.param1 = (Integer) 1;
                event.param2 = param2;
                JSONObject json = (JSONObject) param2;
                String url = json.optString("url", "");
                mDownloadEvents.put(url, event);
                // checkInstallApk(json);
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mRecommendListAdapter.notifyDataSetChanged();
                    }
                });

            } else if (-1 == (Integer) param1)
            {
                showSDCardError();
            }
            else if (-2 == (Integer) param1)
            {
                showDownloadLongClick(param2);
            }
            else if (0 == (Integer) param1)
            {
                DownloadEvent event = new DownloadEvent();
                event.id = DownLoaderUtil.Activity_Event_FileDownload_Info;
                event.param1 = param1;
                event.param2 = param2;
                String url = (String) param2;
                mDownloadEvents.put(url, event);
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mRecommendListAdapter.notifyDataSetChanged();
                        Toast.makeText(FavoriteActivity.this, "您的网络不给力啊，无法继续下载请调整好了在点我。", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } else if (DownLoaderUtil.Activity_Event_FileDownload_Pause.equals(id))
        {
            String url = (String) param2;
            DownloadEvent event = new DownloadEvent();
            event.id = DownLoaderUtil.Activity_Event_FileDownload_Pause;
            event.param1 = param1;
            event.param2 = param2;
            mDownloadEvents.put(url, event);
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    mRecommendListAdapter.notifyDataSetChanged();
                }
            });
        }
        else if (DownLoaderUtil.Activity_Event_FileDownload_Start.equals(id))
        {
            String url = (String) param2;
            DownloadEvent event = new DownloadEvent();
            event.id = DownLoaderUtil.Activity_Event_FileDownload_Start;
            event.param1 = param1;
            event.param2 = param2;
            mDownloadEvents.put(url, event);
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    mRecommendListAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    @Override
    public void onAllReady()
    {
        if (BaseApplication.getInstance().isNeedReloadGameInfo())
        {
            finish();
        } else
        {
            boolean isGame = getIntent().getBooleanExtra("IsGame", true);

            mDownloadEvents.clear();
            if (mMainPagerAdapter == null)
            {
                ArrayList<LinearLayout> views = new ArrayList<LinearLayout>();
                LayoutInflater mInflater = LayoutInflater.from(this);

                mRecommendLayout = (LinearLayout) mInflater.inflate(R.layout.main_recommend_list_viewpager_item, null);
                mRecommendListView = (UpdateFreshListView) mRecommendLayout.findViewById(R.id.lv_recommend);
                mRecommendListAdapter = new RecommendListAdapter(this);
                mRecommendListView.setAdapter(mRecommendListAdapter);
                mRecommendListView.setOnItemClickListener(mRecommendListAdapter);
                mRecommendListView.setIsShowLoadMoreFooter(false);
                views.add(mRecommendLayout);

                mCheatsLayout = (LinearLayout) mInflater.inflate(R.layout.main_cheats_list_viewpager_item, null);
                mCheatsListView = (UpdateFreshListView) mCheatsLayout.findViewById(R.id.lv_cheats);
                mCheatsListAdapter = new CheatsListAdapter(this);
                mCheatsListView.setAdapter(mCheatsListAdapter);
                mCheatsListView.setIsShowLoadMoreFooter(false);
                mCheatsListView.setOnItemClickListener(mCheatsListAdapter);
                views.add(mCheatsLayout);

                mMainPagerAdapter = new MainPagerAdapter(views);
                mViewPager.setAdapter(mMainPagerAdapter);
                mViewPager.setOnPageChangeListener(mMainPagerAdapter);

                towardToGame();
            } else
            {
                mRecommendListAdapter.notifyDataSetChanged();
                mCheatsListAdapter.notifyDataSetChanged();
            }
            if (!isGame)
            {
                mViewPager.setCurrentItem(1, true);
            }
        }

    }

    public void loadArticleFirstImage(JSONObject article, ImageView imageview)
    {
        try
        {
            JSONArray contents = new JSONArray(article.getString("content"));
            for (int i = 0; i < contents.length(); i++)
            {
                JSONObject content = contents.getJSONObject(i);
                String type = content.getString("type");
                if ("image".equals(type))
                {
                    String key = content.getString("content");
                    int id = article.getJSONObject("info").getJSONArray(key).getJSONObject(0).getInt("id");
                    String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                            .append("articles/blob?ref=")
                            .append(id).toString();
                    imageViewLoadInternetResource(imageview, imageurl, R.drawable.nopicture);

                    imageview.setTag(imageurl);
                    break;
                }
            }
        }
        catch (Exception e)
        {}
    }

    private View mGameButton;
    private TextView mGame;
    private View mArticleButton;
    private TextView mArticle;
    private HashMap<String, DownloadEvent> mDownloadEvents = new HashMap<String, DownloadEvent>();

    private void towardToGame()
    {
        mViewPager.setCurrentItem(0, true);
        mGameButton.setBackgroundResource(R.drawable.game_detail_selected_tab_bg);
        mGame.setTextColor(getResources().getColor(R.color.game_detial_tab_text_color));
        mArticleButton.setBackgroundColor(0xff000000);
        mArticle.setTextColor(0xFFFFFFFF);
    }

    private void towardToStrategy()
    {
        mViewPager.setCurrentItem(1, true);
        mArticleButton.setBackgroundResource(R.drawable.game_detail_selected_tab_bg);
        mArticle.setTextColor(getResources().getColor(R.color.game_detial_tab_text_color));
        mGameButton.setBackgroundColor(0xff000000);
        mGame.setTextColor(0xFFFFFFFF);
    }

}
